<?php
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response as FacadesResponse;
class AuthController extends BaseController {
	
	protected $layout = 'layouts.master';

	/**
	 * 测试看用户是否已经登录
	 */
	public function checkAuth() {
		return $this->makeView('general.200', array (
			"user" => ["id" => Auth::user()->id]
		), 200 );
	}
	
	/**
	 * TODOS
	 * - move the custom validators into a central location
	 */
	public function forgotPwd() {
		if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
			$account = Input::get ( 'username' );
			if (preg_match ( "/^1[3-8]\d{9}$/", $account )) {
				$account_type = 'mobile';
			} else {
				$account_type = 'email';
			}
			// Validation
			$rules = array ();
			$messages = array();
			$post = Input::all ();
			Validator::extend ( 'code', function ($attr, $value, $parameters) use($account_type, $post){
				$phone = Activation::where ( 'token', $post['code'] )->where ( 'expired', '>', time () )->pluck ($account_type);
				if ($phone) {
					return Input::get ( 'username' ) == $phone;
				} else {
					return false;
				}
			} );
			if ($account_type == 'mobile') {
				// mobile
				Validator::extend ( 'username', function ($attr, $value, $parameters) {
					return preg_match ( "/^1[3-8]\d{9}$/", $value );
				} );

				$rules = array(
						'username' => 'username|exists:user,phone',
						'code' => 'required|code'
					);
				$messages = array(
						'username.username' => '手机格式不正确',
						'username.exists' => '该手机账户不存在',
						'code.required' => '请输入验证码',
						'code.code' => '验证码错误或超过有效期'
					);
				
			} else {
				// email
				$rules = array(
						'username' => 'required|email|exists:user,email',
						'code' => 'required|code'
					);
				$messages = array(
						'username.required' => '请输入邮箱或手机号',
						'username.email' => '邮箱格式不正确',
						'username.exists' => '该邮箱账户不存在',
						'code.required' => '请输入验证码',
						'code.code' => '验证码错误或超过有效期'
					);
			}
			
			$validator = Validator::make ( $post, $rules, $messages );
			if ($validator->fails()) {
				// the given data did not pass validation
				return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
			}
			if($account_type == 'mobile') $account_type = 'phone';
 			$user = User::where ( $account_type, $account )->first ();
			$phone = Activation::where ( 'token', $post['code'] )->where ( 'expired', '>', time () )->first();
			$phone->token = $user->id.time();
			$phone->save();
 			$redirect_url = URL::route ( 'auth.forgotpwd.resetpwd', $phone->token);
				$success_msg = '验证完成。';
//				$user->setPasswordAttribute ( $new_pwd );
				return $this->makeView('general.200', array (
						"status_code" => 302,
						'redirect_url' => $redirect_url,
						'success_messages' => $success_msg, 
						'uid' => $phone->token
				), 200 );
 		} else {
 			$this->layout->content = View::make ( 'auth.reset_pwd' );
 		}
	}
	
	/**
	 * 发送验证码
	 *
	 * @return string
	 */
	public function sendCode() {
		$account = Input::get ( 'username' );
		if (preg_match ( "/^1[3-8]\d{9}$/", $account )) {
			$account_type = 'phone';
		} else {
			$account_type = 'email';
		}
		$rules = array ();
		$messages = array();
		$posts = Input::all ();
			
		if ($account_type == 'phone') {
			// mobile
			Validator::extend ( 'username', function ($attr, $value, $parameters) {
				return preg_match ( "/^1[3-8]\d{9}$/", $value );
			} );
			$rules['username']='username';
			$messages['username.username']='手机号格式不正确';
		} else {
			// email
			$rules['username'] = 'required|email';
			$messages['username.required'] = '请输入邮箱';
			$messages['username.email'] = '邮箱格式不正确';
		}
			
		$validator = Validator::make ( $posts, $rules, $messages );
		if ($validator->fails()) {
			// the given data did not pass validation
			return FacadesResponse::json (
					array (
							"status_code" => 400,
							'error_messages' => $validator->errors()
					), 400 );
		}		
	
		$phone = $posts['username'];
		$requestTimeArr = Session::get($phone);
		if (is_array($requestTimeArr)) {
			foreach($requestTimeArr as $key => $value) {
				$times = time()-$requestTimeArr[$key];
				if($times>3600){
					Session::forget($phone.'.'.$key);
				}
			}
			if(count($requestTimeArr)>=3) {
				return $this->makeView('errors.400',['username' => ['一小时内只能获取三次验证码']],400);
			}else{
				Session::push($phone,time());
			}
		}else{
			Session::push($phone,time());
		}
		$validator = Validator::make ($posts, $rules, $messages );
		if ($validator->fails()) {
			// the given data did not pass validation
			return $this->makeView(
					'errors.400',
					$validator->errors(),
					400
			);
		} else {
			if($account_type == 'phone'){
				$activation = Activation::firstOrNew ( array (
						'mobile' => $phone
				) );
			}else{
				$activation = Activation::firstOrNew ( array (
						'email' => $phone
				) );
			}
				
			$activation->token = UtilsHelper::generateRandomNumbers ( 5 );
			$activation->expired = time () + 3600;
			$activation->save ();
			try {
				if($account_type == 'phone')
				{
					//短信文案
					MsgHelper::sendSMS (
							$phone,
							sprintf("【律团网】您的验证码为%s,请尽快进行验证（一小时内有效），并勿向其他人泄露您的验证码。",
									$activation->token));
					
					return $this->makeView('general.200', '验证码已发送到您的手机', 200);
				}else{
					Mail::send ( 'emails.auth.resetpwd', [ 
							'pwd' => $activation->token 
					], function ($message) use($phone) {
						$message->to ( $phone )->subject ( '重置密码' );
					} );
					
					return $this->makeView('general.200', '验证码已发送到您的邮箱', 200);
				}
			} catch(Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'获取验证码失败，请稍后再试。',
						503
				);
			}
		}
	}
	
	public function resetpwd($uid){
		$active = Activation::where('token', $uid)->first();
		if(!$active){
			return Redirect::route('auth.resetpwd');
		}
		if($active->expired < time()){
			return Redirect::route('auth.resetpwd');
		}
		if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
			$post = Input::all();
			Validator::extend('equal', function($attr, $value, $parameters) use($post){
				return ($post['password_1'] == $post['password_2']);
				
			});
			$rules = array (
				'password_1' => 'required|equal|between:6,18'
			);
			$messages = array(
				'password_1.required' => '请填写密码',
				'password_1.between' => '密码长度在:min到:max之间',
				'password_1.equal' => '两次密码不一致'
			);
			$validator = Validator::make ( $post, $rules, $messages );
			if ($validator->fails()) {
				// the given data did not pass validation
				return $this->makeView(
						'errors.400',
						$validator->errors(),
						400
				);
			}
			try{
				$active->expired = time();
				$user = $active->mobile? User::where('phone', $active->mobile)->first():User::where('phone', $active->email)->first();
				$oldPwd = $user->password;
				$user->setPasswordAttribute ( $post['password_1'] );
				$user->reset_time = time ();
				$user->save ();
				$active->save();
                //同步修改环信密码
				$newPwd = $user->password;
				$result = new Easemob();
				$options = array(
						'username' => $user->id,
						'password' => $oldPwd,
						'newpassword' => $newPwd
					);
				$result_re = $result->editPassword($options);
			}catch(Exception $ex){
				Log::error($ex);
				return $this->makeView('errors.503', '修改密码失败，请稍后再试', 503);
			}
			return $this->makeView('general.200' ,'修改成功', 200);
		}else{
			return $this->makeView('auth.reset_pwd_2' ,['uid' => $uid]);
		}
		
	}
}
